package com.qipay.api.callback.controller.v1;

import com.qipay.baas.model.Order;
import com.qipay.order.service.OrderService;
import com.qipay.sp.SpConfigService;
import com.qipay.utils.MD5Util;
import com.qipay.utils.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 麻袋回调
 */
@RestController
@RequestMapping("/callback/v1/madai")
public class MdCallbackController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
	OrderService orderService;

    @Autowired
	SpConfigService spConfigService;

    @RequestMapping(value = "/wx")
    private String unionCreate(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, String> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);

        if(params!=null&&"1".equals(params.get("status"))){
            String tradeNo = params.get("sdorderno");
            Order order = orderService.getByTradeNo(tradeNo);
            if(order==null) {
                logger.info("回调失败：查无此订单="+tradeNo);
                return "fail";
            }
            Map<String, Object> keyValues = spConfigService.getKeyValues(order.getSpId());
            String key = keyValues.get("key").toString();
            String fromSign = params.get("sign");
            String signStr =generateStr(params,key);
            String mySign = MD5Util.sign(signStr,"utf-8").toLowerCase();
            if(fromSign.equals(mySign)){
                orderService.setOrderSuccess(order.getId(), null);
                return "success";
            }else {
                logger.info("回调失败：签名sign不一致，tradeNo="+tradeNo);
            }
        }
        return "fail";
    }

    public String generateStr(Map<String, String>params ,String key){
        return "customerid="+params.get("customerid")+"&status="+params.get("status")+"&sdpayno="+params.get("sdpayno")+
                "&sdorderno="+params.get("sdorderno")+"&total_fee="+params.get("total_fee")+
                "&paytype="+params.get("paytype") +"&"+key;
    }

}
